package goutil

import (
	"fmt"
	"io"
	"os"
	"time"
)

const (
	ConfigPathDefault = "config/app.yml"
	AppNameDefault    = "app"
)

type GoutilCore struct {
	Args   *GoutilArgs
	Config *GoutilConfig
	Log    *GoutilLog
}

// 判断文件是否存在
func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}

func (s *GoutilCore) newConfigDefault() {
	// TODO: 判断字段存在
	conf := s.Args.GoutilConfigPath
	if conf == "" {
		conf = ConfigPathDefault
	}
	if !FileExist(conf) {
		fmt.Printf("Default profile not found: %s\n", conf)
		return
	}
	s.Config = NewConfig(conf)
	subs := s.Args.GoutilConfigSub
	if len(subs) == 0 {
		subs = s.Config.GetStringSlice("goutil.config.sub")
	}
	s.Config.SetSubConfigs(subs...)
}

func (s *GoutilCore) newLogDefault() {
	writers := make([]io.Writer, 0, 2)
	writers = append(writers, ConsoleFormater(os.Stdout, false))
	if s.Config != nil {
		path := s.Config.GetString("goutil.log.path")
		if path != "" {
			rfw := NewRotateFileWriter(path, s.Config.GetString("goutil.log.prefix"),
				time.Hour*time.Duration(s.Config.GetInt("goutil.log.rotationHour")),
				time.Hour*time.Duration(s.Config.GetInt("goutil.log.expiryHour")))
			if rfw != nil {
				writers = append(writers, rfw)
			}
		}
	}
	s.Log = NewLogWithWriters(writers...)
}

// 默认初始化
// tips:
//  - 命令行和配置文件同时设置时, 优先使用命令行的配置
func NewCoreDefault() *GoutilCore {
	g := GoutilCore{}
	g.Args = NewArgs(true)
	g.newConfigDefault()
	g.newLogDefault()

	appName := ""
	if g.Config != nil {
		g.Config.GetString("goutil.app.name")
		if appName == "" {
			appName = AppNameDefault
		}
	}
	return &g
}
